import {reqGetCode, reqLogout, reqUserInfo, reqUserLogin, reqUserRegister} from "@/api";
import {getToken, removeToken, setToken} from '@/utils/token'
const state={
    code:'',
    token:getToken(),
    userInfo:{}
}
const mutations={
    GETCODE(state,code){
        state.code=code
    },
    USERLOGIN(state,token){
        state.token=token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo=userInfo
    },
    USERLOGOUT(state){
        //把仓库中相关用户信息和本地存储清空
        state.token='',
            state.userInfo={}
            removeToken()
    }
}
const actions={
    //获取验证码
    async getCode({commit},phone){
        let result= await reqGetCode(phone)
        if (result.code==200){
            commit('GETCODE',result.data)
            return 'ok'
        }else {
           return Promise.reject(new Error('fail'))
        }
    },
    //用户注册,没有返回数据
    async userRegister({commit},user){
        let result = await reqUserRegister(user)
        console.log(result)
        if (result.code==200){
            return 'ok'
        }else {
            return Promise.reject(new Error('fail'))
        }
    },
    //用户登录
    async userLogin({commit},data){
       let result = await reqUserLogin(data)
        //token是某一个用户的唯一标识，像uuid，将来经常通过toke向服务器返回信息
        if (result.code==200){
            commit('USERLOGIN',result.data.token)
            //持久化token
           setToken(result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('fail'))
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
      let result=await reqUserInfo()
        console.log(localStorage.getItem('TOKEN'))
        if (result.code==200){
            commit('GETUSERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('fail'))
        }
    },
    //退出登录
    async userLogout({commit}){
        let result=await reqLogout()
        if (result.code==200){
            commit('USERLOGOUT')
            return 'ok'
        }else {
            return Promise.reject(new Error('fail'))
        }
    }
}
const getters={}
export default {
    state,
    actions,
    mutations,
    getters
}